package com.tinyspot.concrete.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author Tinyspot
 * @date 2023-01-06 20:58
 */
@Component
@Slf4j
public class PostGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        if (queryParams.containsKey("message")) {
            log.info("前置处理");
            ServerHttpResponse response = exchange.getResponse();
            DataBuffer dataBuffer = response.bufferFactory().wrap("pre-run".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> log.info("post run...")));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
